import React, {useEffect, useState} from 'react';
import {
    Breadcrumb,
    Button,
    Col,
    Form,
    Input,
    Layout, message, Modal,
    Popconfirm,
    Row,
    Select,
    Space
} from "antd";
import {useNavigate, useParams} from "react-router-dom";
import {Content} from "antd/es/layout/layout";
import MyTable from "../../../../pages/Mytable";
import {getAllInterFaceByPage,findInterfaceById,updateInterfaceById,deleteInterFaceById,addInterface} from "../../../../api/interfaces";
import {getSystemModuleBySystemId} from "../../../../api/systemModule";
const Option = Select.Option;
function System() {
    const navigate = useNavigate()
    const {id} = useParams()
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [edit, setEdit] = useState(false);
    const requestMethods= ["GET", "POST", "PUT", "PATCH", "DELETE", "COPY", "HEAD", "OPTIONS", "LINK", "UNLINK", "PURGE", "LOCK", "UNLOCK", "PROPFIND", "VIEW"];
    const responseType= ["JSON", "XML","HTML"];
    const [systemModule, setSystemModule] = useState([]);
    const columns = [
        {
            title: '接口名称',
            dataIndex: 'name',
        },
        {
            title: '接口路径',
            dataIndex: 'path',
        },
        {
            title: '请求方式',
            dataIndex: 'request',
        },
        {
            title: '开发人员',
            dataIndex: 'person',
        },
        {
            title: '操作',
            dataIndex: 'repayment',
            render: (_, record) => (<Space>
                <Button type='primary' onClick={async () => {
                    const {data:res} = await findInterfaceById(record.id)
                    interfaceInfoForm.setFieldsValue(res.data)
                    message.success(res.msg)
                    setEdit(true)
                    setIsModalVisible(true)
                }}>编辑</Button>
                <Popconfirm title="确认删除？" okText="确认" cancelText="取消" onConfirm={async () => {
                    const{data:res} = await deleteInterFaceById(record.id)
                    message.success(res.msg)
                    setPage({...page, current: 1})
                }}>
                    <Button type='danger'>删除</Button></Popconfirm>
            </Space>)
        }
    ];
    const [interfaceInfo, setInterfaceInfo] = useState({
        "name": "",
        "path": "",
        "request":""
    })
    const [searchForm] = Form.useForm();
    const [interfaceInfoForm] = Form.useForm();
    const [page, setPage] = useState({
        "system_id": Number(id),
        "current": 1,
        "pageSize": 10
    })
    const pagination = {
        onShowSizeChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        onChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        showSizeChanger: true,
        total,
        current: page.current,
        pageSize: page.pageSize,
        defaultPageSize: 10,
        pageSizeOptions:
            [5, 10, 15, 20]
    }
    const paginationChange = async (current, pageSize) => {
        setPage({
            system_id: Number(id),
            pageSize,
            current
        })
    }
    useEffect(() => {
        setLoading(true)
        getAllInterFaceByPage({...page,...interfaceInfo}).then(response =>{
            const {records, total} = response.data.data
            setTotal(total)
            setData(records)
            setLoading(false)
        })
    }, [page, interfaceInfo]);


    useEffect(()=>{
        getSystemModuleBySystemId(Number(id)).then(response =>{
            setSystemModule(response.data.data)
        })
        // eslint-disable-next-line
    },[])
    return (
        <Layout style={{padding: '0 24px 24px'}}>
            <Breadcrumb style={{margin: '16px 0'}}>
                <Breadcrumb.Item onClick={() => navigate("/main")}>首頁</Breadcrumb.Item>
                <Breadcrumb.Item onClick={() => navigate("/main/interfaces")}>接口管理</Breadcrumb.Item>
                <Breadcrumb.Item>接口配置</Breadcrumb.Item>
            </Breadcrumb>
            <Content
                className="site-layout-background"
                style={{
                    padding: 24,
                    margin: 0,
                    minHeight: 280,
                }}
            >
                <Form
                    name="basic"
                    autoComplete="off"
                    form={searchForm}
                    style={{
                        marginBottom: '10px'
                    }}
                    onFinish={(values) => {
                        setInterfaceInfo(values)
                        setPage({...page, current: 1})
                    }}
                >
                    <Row gutter={24}>
                        <Col span={8}><Form.Item
                            label="接口名称"
                            name='name'
                        >
                            <Input/>
                        </Form.Item></Col>

                        <Col span={8}>
                            <Form.Item
                                label="接口路径"
                                name='path'
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="请求方式"
                                name='request'
                            >
                                <Select>
                                    <Select.Option value="POST">POST</Select.Option>
                                    <Select.Option value="DELETE">DELETE</Select.Option>
                                    <Select.Option value="PUT">PUT</Select.Option>
                                    <Select.Option value="GET">GET</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col
                            span={24}
                            style={{
                                textAlign: 'right',
                            }}
                        >
                            <Space>
                                <Button type="primary" onClick={() => {
                                    setEdit(false)
                                    setIsModalVisible(true)
                                }}>
                                    添加接口
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button
                                    onClick={async () => {
                                        searchForm.resetFields()
                                        const formValue = await searchForm.validateFields()
                                        setInterfaceInfo(formValue)
                                        setPage({...page, current: 1})
                                    }}
                                >
                                    重置
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <MyTable
                    columns={columns}
                    dataSource={data}
                    pagination={pagination}
                    bordered
                    loading={loading}
                />
                <Modal title={edit ? '编辑接口' : '添加接口'} visible={isModalVisible} closable={false} footer={null}>
                    <Form
                        name="systemInfo"
                        autoComplete="off"
                        layout={'vertical'}
                        form={interfaceInfoForm}
                        onFinish={async (values) => {
                            console.log(values)
                            if(edit){
                                const {data: res} = await updateInterfaceById(values)
                                message.success(res.msg)
                            }else {
                                const {data: res} = await addInterface({...values,system_id:Number(id)})
                                message.success(res.msg)
                            }
                            setIsModalVisible(false)
                            interfaceInfoForm.resetFields()
                            setEdit(false)
                            setPage({...page})
                        }}
                    >
                        <Form.Item
                            label="id"
                            name="id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="system_id"
                            name="system_id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="接口名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入接口名称',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="接口路径"
                            name="path"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入接口路径',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="开发人员"
                            name="person"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择开发人员',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="请求方式"
                            name="request"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入请求方式',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    requestMethods.map(method =>{
                                        return <Option key={method} value={method}>{method}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="响应方式"
                            name="response"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入响应方式',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    responseType.map(method =>{
                                        return <Option key={method} value={method}>{method}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="模块名称"
                            name="module_id"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择模块名称',
                                },
                            ]}
                        >
                            <Select>
                                {systemModule.map(module =>{
                                    return <Option key={module.id} value={module.id}>{module['module_name']}</Option>
                                })}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        ><Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button type="default" onClick={async () => {
                                interfaceInfoForm.resetFields()
                                setEdit(false)
                                setIsModalVisible(false)
                            }}>
                                取消
                            </Button>
                        </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
}

export default System;